package com.roomio.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.roomio.core.security.model.User;
import com.roomio.core.security.service.UserInfoService;
import com.roomio.domain.Group;
import com.roomio.service.GroupInfoService;
import com.roomio.web.dto.UIGroup;

@RequestMapping("/groupinfoes")
@Controller
public class GroupInfoController extends BaseSpringController {
	
	@Autowired
	private GroupInfoService groupInfoService; 
	@Autowired
	private UserInfoService userInfoService; 
	
	 @RequestMapping(value="add")
    public String create(@Valid UIGroup group, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, group);
            return "groupinfoes/create";
    }
        uiModel.asMap().clear();
        Group modelgroup = new Group();
        modelgroup.setName(group.getGroupName());
        
        modelgroup.setGroupOwner(getCurrentUser());
        modelgroup.addUser(getCurrentUser());
        List<String> users = group.getUsers();
        for (String string : users) {
        	User user = userInfoService.findByEmail(string);
        	if(user!= null){
        		 modelgroup.addUser(user);
        	}
        	
		}
        groupInfoService.persist(modelgroup);
       //return "redirect:/groupinfoes/" + encodeUrlPathSegment(group.getId().toString(), httpServletRequest);
        return "redirect:/groupinfoes";
    }
    
    @RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel) {
        populateEditForm(uiModel, new UIGroup());
        return "groupinfoes/create";
    }
    
    @RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Long id, Model uiModel) {
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("groupinfo", groupInfoService.findGroupInfo(id));
        uiModel.addAttribute("itemId", id);
        return "groupinfoes/show";
    }
    
    @RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("groupinfoes", groupInfoService.findGroupInfoEntries(firstResult, sizeNo));
            float nrOfPages = (float) groupInfoService.countGroupInfoes() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
        	List<Group> groupList = groupInfoService.findGroupsByOwnerName(getCurrentUser().getEmail());
        	if(groupList!= null && groupList.size() >0){
            uiModel.addAttribute("groupinfoes", groupList);
        	}else{
        		return "redirect:/groupinfoes?form";
        	}
        }
        addDateTimeFormatPatterns(uiModel);
        return "groupinfoes/list";
    }
    
    @RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid Group group, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, group);
            return "groupinfoes/update";
        }
        uiModel.asMap().clear();
        groupInfoService.update(group);
        return "redirect:/groupinfoes/" + encodeUrlPathSegment(group.getId().toString(), httpServletRequest);
    }
    
    @RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id") Long id, Model uiModel) {
        populateEditForm(uiModel, groupInfoService.findGroupInfo(id));
        return "groupinfoes/update";
    }
    
    @RequestMapping(value = "/{id_}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id_") Long id_, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        groupInfoService.remove(id_);
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/groupinfoes";
    }
    
    void addDateTimeFormatPatterns(Model uiModel) {
        uiModel.addAttribute("groupInfo_createddate_date_format", DateTimeFormat.patternForStyle("M-", LocaleContextHolder.getLocale()));
    }
    
    void populateEditForm(Model uiModel, Group group) {
        uiModel.addAttribute("groupInfo", group);
        addDateTimeFormatPatterns(uiModel);
    }
    
    void populateEditForm(Model uiModel, UIGroup group) {
        uiModel.addAttribute("groupInfo", group);
        addDateTimeFormatPatterns(uiModel);
    }
    
    
	
	
}
